- Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path186. Reverse Words in a String II.c
65 lines (45 loc) · 1.32 KB
/
186. Reverse Words in a String II.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
186. Reverse Words in a String II
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?
Related problem: Rotate Array
*/
voidswap(char*a, char*b) {
charc=*a;
*a=*b;
*b=c;
}
voidreverse(char*s, intstart, intend, intw) {
inti, j;
for (i=start, j=end; i <= j; i++, j--) {
swap(&s[i], &s[j]);
if (w&&s[i] ==' ') {
reverse(s, start, i-1, 0);
start=i+1;
}
if (w&&s[j] ==' ') {
reverse(s, j+1, end, 0);
end=j-1;
}
}
if (w&&start<end) reverse(s, start, end, 0);
}
voidreverseWords(char*s) {
reverse(s, 0, strlen(s) -1, 1);
}
/*
Difficulty:Medium
Total Accepted:30.2K
Total Submissions:110.3K
Companies Microsoft Amazon Uber
Related Topics String
Similar Questions
Reverse Words in a String
Rotate Array
*/